package com.xunyin.modules.wechatshop.rest;


import com.github.pagehelper.util.StringUtil;
import com.xunyin.api.ApiResult;
import com.xunyin.common.bean.LocalUser;
import com.xunyin.common.interceptor.AuthCheck;
import com.xunyin.enums.StatusEnum;
import com.xunyin.enums.YesOrNoEnum;
import com.xunyin.modules.common.param.AddressDetailParam;
import com.xunyin.modules.common.param.AddressRequest;
import com.xunyin.modules.mtaddress.domain.MtAddress;
import com.xunyin.modules.mtaddress.service.AddressService;
import com.xunyin.modules.mtorderaddress.service.dto.AddressDto;
import com.xunyin.modules.mtregion.domain.MtRegion;
import com.xunyin.modules.mtregion.service.mapper.MtRegionMapper;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.YxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 收货地址controller
 * Copyright (C) 2022-2023
 * All rights reserved, Designed By www.tonetn.com
 * 注意：
 * 本软件为讯音云商开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
@Slf4j
@RestController
@Api(value = "收货地址相关", tags = "共享空间:收货地址接口相关")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientAddressController {

    /**
     * 收货地址服务接口
     * */
    private final AddressService addressService;

    //@Resource
    private final MtRegionMapper mtRegionMapper;

    private final YxUserService userService;

    /**
     * 保存收货地址
     */
    @ApiOperation(value = "保存收货地址", notes="保存会员的收货地址")
    @RequestMapping(value = "/address/save", method = RequestMethod.POST)
    @CrossOrigin
    @AuthCheck
    public ApiResult<String> save(HttpServletRequest request, @RequestBody AddressRequest address)  {

        String name = address.getName() == null ? "" : address.getName();
        String mobile = address.getMobile() == null ? "" : address.getMobile();
        Integer provinceId = address.getProvinceId() == null ? 0 : address.getProvinceId();
        Integer cityId = address.getCityId() == null ? 0 : address.getCityId();
        Integer regionId = address.getRegionId() == null ? 0 : address.getRegionId();
        String detail = address.getDetail() == null ? "" : address.getDetail();
        String status = address.getStatus() == null ? StatusEnum.ENABLED.getKey() : address.getStatus();
        String isDefault = address.getIsDefault() == null ? "" : address.getIsDefault();
        Integer addressId = address.getAddressId() == null ? 0 : address.getAddressId();

        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());

        MtAddress mtAddress = new MtAddress();
        mtAddress.setId(addressId);
        mtAddress.setName(name);
        mtAddress.setMobile(mobile);
        mtAddress.setProvinceId(provinceId);
        mtAddress.setCityId(cityId);
        mtAddress.setRegionId(regionId);
        mtAddress.setDetail(detail);
        mtAddress.setStatus(status);
        mtAddress.setUserId(user.getUid().intValue());
        mtAddress.setIsDefault(isDefault);

        addressService.saveAddress(mtAddress);
        return ApiResult.ok("保存成功");
        //return getSuccessResult(true);
    }



    /**
     * 获取个人收货地址列表
     */
    @ApiOperation(value="获取个人收货地址列表", notes="获取个人收货地址列表")
    @RequestMapping(value = "/address/list", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Map<String, Object>> list(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();

        param.put("status", StatusEnum.ENABLED.getKey());
        List<MtAddress> addressList = addressService.queryListByParams(param);

        List<AddressDto> dataList = new ArrayList<>();
        for (MtAddress mtAddress : addressList) {
            AddressDto dto = new AddressDto();
            BeanUtils.copyProperties(mtAddress, dto);

            String province = "";
            String city = "";
            String region = "";

            if (dto.getProvinceId() > 0) {
                MtRegion mtProvince = mtRegionMapper.selectById(dto.getProvinceId());
                if (mtProvince != null) {
                    province = mtProvince.getName();
                }
            }
            if (dto.getCityId() > 0) {
                MtRegion mtCity = mtRegionMapper.selectById(dto.getCityId());
                if (mtCity != null) {
                    city = mtCity.getName();
                }
            }
            if (dto.getCityId() > 0) {
                MtRegion mtRegion = mtRegionMapper.selectById(dto.getRegionId());
                if (mtRegion != null) {
                    region = mtRegion.getName();
                }
            }

            dto.setProvinceName(province);
            dto.setCityName(city);
            dto.setRegionName(region);

            dataList.add(dto);
        }

        result.put("list", dataList);
        return ApiResult.ok(result);
        //return getSuccessResult(result);
    }



    /**
     * 获取收货地址详情
     */
    @ApiOperation(value="获取收货地址详情", notes="根据ID获取会员收货地址详情")
    @RequestMapping(value = "/address/detail", method = RequestMethod.POST)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Map<String, Object>> detail(HttpServletRequest request, @RequestBody AddressDetailParam addressDetailParam) throws InvocationTargetException, IllegalAccessException {
        // String token = request.getHeader("Access-Token") == null ? "" : request.getHeader("Access-Token");
        String addressIdStr = addressDetailParam.getAddressId() == null ? "0" : addressDetailParam.getAddressId();
        Integer addressId = 0;
        if (StringUtil.isNotEmpty(addressIdStr)) {
            addressId = Integer.parseInt(addressIdStr);
        }

        Map<String, Object> result = new HashMap<>();

        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());

        MtAddress mtAddress = null;
        if (addressId > 0) {
            mtAddress = addressService.detail(addressId);
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("userId", user.getUid().intValue());
            params.put("isDefault", YesOrNoEnum.YES.getKey());
            List<MtAddress> addressList = addressService.queryListByParams(params);
            if (addressList.size() > 0) {
                mtAddress = addressList.get(0);
            }
        }

        if (mtAddress != null) {
            if (mtAddress.getUserId().equals(user.getUid().intValue())) {
                AddressDto dto = new AddressDto();
                BeanUtils.copyProperties(mtAddress, dto);
                String province = "";
                String city = "";
                String region = "";
                if (dto.getProvinceId() > 0) {
                    MtRegion mtProvince = mtRegionMapper.selectById(dto.getProvinceId());
                    if (mtProvince != null) {
                        province = mtProvince.getName();
                    }
                }
                if (dto.getCityId() > 0) {
                    MtRegion mtCity = mtRegionMapper.selectById(dto.getCityId());
                    if (mtCity != null) {
                        city = mtCity.getName();
                    }
                }
                if (dto.getRegionId() > 0) {
                    MtRegion mtRegion = mtRegionMapper.selectById(dto.getRegionId());
                    if (mtRegion != null) {
                        region = mtRegion.getName();
                    }
                }

                dto.setProvinceName(province);
                dto.setCityName(city);
                dto.setRegionName(region);

                result.put("address", dto);
            }
        }

        //return getSuccessResult(result);
        return ApiResult.ok(result);
    }

}
